<script setup>
import {computed, reactive, ref} from "vue";
import DictQuantifySelector from "@/components/DictQuantifySelector.vue";
import {message} from "ant-design-vue";
import webConfig from "@/GlobalParas.js";
import axios from "axios";
import {decrypt} from "@/util/StringOper.js";

let quantifyObj = reactive({})
quantifyObj.selectedItem = ''
quantifyObj.selectedItemInfo = ''
quantifyObj.finish_time = ''
quantifyObj.allocateUsers = []
quantifyObj.info = '请输入业绩内容'
quantifyObj.fileList = []


quantifyObj.allocateUsers.push(
    {
      "userId": decrypt(localStorage.getItem("userId")),
      "userName": decrypt(localStorage.getItem("realName")),
      "marks": quantifyObj.selectedItem.marks,
      "isShowSelector": false
    }
)
for (let i = 0; i < 9; i++) {
  let allocateUser = {}
  allocateUser.userId = ""
  allocateUser.userName = ""
  allocateUser.marks = ""
  allocateUser.isShowSelector = false
  quantifyObj.allocateUsers.push(allocateUser)
}

let allocatedMarks = computed(() => {
  let rs = 0;
  quantifyObj.allocateUsers.forEach(item => {
    if (item.marks !== "") {
      rs += (item.marks - 0);
    }
  })
  return rs;
})

// console.log(localStorage.getItem("allSystemUsers"));
let allUsers = JSON.parse(decrypt(localStorage.getItem("allSystemUsers")));
console.log(allUsers)
let usersForSelect = [];
allUsers.forEach(item => {
  let userObj = {};
  userObj.value = item.tableKey;
  userObj.label = item.realName;
  usersForSelect.push(userObj);
})

let options = ref(usersForSelect);

const onSearch = searchText => {
  options = usersForSelect.filter(item => {
    return item.label.indexOf(searchText) !== -1
  })
};

const onSelect = (value, option, userObj) => {

  // console.log('value', value);
  // console.log('option', option);
  // console.log('userObj',userObj);

  userObj.userName = option.label;
  userObj.isShowSelector = false;

  let tempUserCheck = quantifyObj.allocateUsers.filter(item => {
    return item.userId === value;
  })
  if (tempUserCheck.length > 1) {
    message.error(option.label + "已经存在.");
    userObj.userId = ""
    userObj.userName = ""
  }
};

const marksChanged = (value, userObj) => {
  // console.log(value);
  // console.log(userObj);
  if (userObj.userId === "") {
    message.error("请先选择参与人.")
    userObj.marks = "";
  }
  if (allocatedMarks.value > quantifyObj.selectedItem.marks) {
    message.error("分配分值不能超过所选业绩总分.");
    userObj.marks = 0;
  }
  // console.log(allocatedMarks)
}

let userNameTxtOnFocus = (item) => {
  // console.log(item)
  item.isShowSelector = true;
  // console.log(item)
}

let isOpenWin = ref(false);

function QuantifyItemClick(params) {
  quantifyObj.selectedItem = params;
}

function openWin() {
  isOpenWin.value = true;
}

function handleOk() {
  if (quantifyObj.selectedItem === undefined) {
    message.error("请选择业绩类型。")
  } else {
    // console.log(quantifyObj.selectedItem)
    quantifyObj.selectedItemInfo = quantifyObj.selectedItem.quantifyRule
        + "(" + quantifyObj.selectedItem.marks + "分)";
    // console.log(quantifyObj)
    isOpenWin.value = false;
  }
}


const uploadPath = webConfig.postUrl + "/upload";
const handleChange = info => {
  if (info.file.status !== 'uploading') {
    // console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    console.log(fileList.value)
    message.success(`${info.file.name} 上传成功.`);
    fileList.value.forEach(item => {
      item.serverFileName = item.response + "_" + item.name;
      item.url = webConfig.downLoadPath + item.newFileName;
    })
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 上传失败.`);
  }
};
const fileList = ref([]);
const headers = {
  authorization: 'authorization-text',
};


let emit = defineEmits(['addWorkPerformance'])
function onBtnClick() {
  quantifyObj.fileList = fileList.value
  // console.log(quantifyObj);
  emit("addWorkPerformance", quantifyObj)


  // let params = {};
  // params.param = JSON.stringify(quantifyObj);
  // axios.post(webConfig.postUrl + "/workPerformance/addWorkPerformance", params).then(res => {
  //   console.log(res.data);
  // })
}
</script>

<template>
  <a-modal v-model:open="isOpenWin" title="业绩类型选择" @ok="handleOk" width="800px">
    <DictQuantifySelector @getSelectedInfo="QuantifyItemClick"></DictQuantifySelector>
  </a-modal>
  <table class="tableClass">
    <tbody>
    <tr>
      <td class="columnTitle">
        完成时间：
      </td>
      <td style="width:120px">
        <a-date-picker v-model:value="quantifyObj.finish_time" value-format="YYYY-MM-DD" style="width:100%"/>
      </td>
      <td style="width:130px">
        <a-button style="margin-left: 5px;float: left;" @click="openWin">选择业绩类型</a-button>
      </td>
      <td>
        <span class="columnInfo">{{ quantifyObj.selectedItemInfo }}</span>
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <table class="allocateInfo">
          <tbody>
          <tr>
            <th style="width:130px">
              参与人
            </th>
            <th>
              分值
            </th>
          </tr>
          <tr v-for="item in quantifyObj.allocateUsers">
            <td>
              <a-auto-complete
                  v-model:value="item.userId"
                  :options="options"
                  :style='{ "width":"100%", "display":item.isShowSelector===false?"none":"" }'
                  placeholder="输入姓名并选择"
                  @select="(a, b)=>onSelect(a,b,item)"
                  @search="onSearch"
              />
              <a-input type="text"
                       :value="item.userName"
                       @focus="userNameTxtOnFocus(item)"
                       :style="{'display':item.isShowSelector===false?'':'none'}"></a-input>
            </td>
            <td>
              <a-input-number v-model:value="item.marks"
                              :min="1"
                              :max="100"
                              @change="(a)=>marksChanged(a, item)"/>
            </td>
          </tr>
          <tr>
            <td style="text-align: center;color:red;font-weight: bold">
              合计
            </td>
            <td style="text-align: center;color:red;font-weight: bold">
              {{ isNaN(allocatedMarks) ? 0 : allocatedMarks }}
            </td>
          </tr>
          </tbody>
        </table>
      </td>
      <td colspan="2" style="vertical-align: top">
        <table class="allocateInfo">
          <tbody>
          <tr>
            <th>
              业绩说明
            </th>
          </tr>
          <tr>
            <td>
              <a-textarea v-model:value="quantifyObj.info" placeholder="Basic usage" :rows="10"/>
            </td>
          </tr>
          <tr>
            <td id="uploadFileInfo">
              <a-upload
                  v-model:file-list="fileList"
                  name="file"
                  :headers="headers"
                  @change="handleChange"
                  accept="image/*,.zip,.rar,.7z"
                  :action="uploadPath"
              >
                <a-button>
                  选择文件上传
                </a-button>
              </a-upload>
            </td>
          </tr>
          </tbody>
        </table>
      </td>
    </tr>
    </tbody>
  </table>
  <a-button @click="onBtnClick" type="primary" style="float: right">提交</a-button>
</template>

<style scoped>
.tableClass {
  background: #FFF;
  width: 100%;
  border-collapse: collapse;
  font-family: "宋体", "Times New Roman", Times, serif;
}

.tableClass td {
  padding-top: 5px;
  padding-left: 5px;
  padding-right: 5px;
}

.columnTitle {
  text-align: right;
  width: 100px;
}

.columnInfo {
  line-height: 120%;
  text-align: left;
}

.allocateInfo {
  border-collapse: collapse;
  width: 100%;
}

.allocateInfo th {
  height: 30px;
  background: #f3f7ff;
}

.allocateInfo td {
  height: 30px;
}

div {
  float: left
}
</style>